<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: [ JRK丶Admin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020/7/17 0026
// +----------------------------------------------------------------------
// | Description:
// +----------------------------------------------------------------------


namespace app\common\subscribes;

use app\api\service\JinDie;
use app\api\service\message;
use app\common\energyApi\Energy;
use app\common\model\tang\Config;
use app\common\model\tang\KwhLog;
use app\common\model\tang\KwhWaterLog;
use app\common\model\tang\Merchant;
use app\common\model\tang\MerchantDayMoney;
use app\common\model\tang\MerchantMoney;
use app\common\model\tang\MerchantMonthMoney;
use app\common\model\tang\MerchantOperate;
use app\common\model\tang\MerchantReadingLog;
use app\common\model\tang\MonthElectricityDegree;
use app\common\model\tang\MonthSoleElectricityLog;
use app\common\model\tang\MonthWaterLog;
use app\common\model\tang\WatchLog;
use app\common\model\tang\WatchMaintain;
use think\facade\Log;

class TaskSubscribe extends Base
{
    /**
     * 定时执行的方法
     */
    public function onTask()
    {
        $start_time = strtotime(date('Y-m-d ' . '06:00:00'));
        $end_time = strtotime(date('Y-m-d ' . '07:40:00'));
        $YesterDay = date("Y-m-d", strtotime("-1 day"));
        $month = date("Y-m", strtotime("-1 month"));
        $monthsss = date("Y-m", strtotime("-2 month"));
        $nowMonth = date("Y-m");
        $day = explode('-',$YesterDay);
        $mon = explode('-',$nowMonth);
        $merchant_list = (new MerchantOperate())->find(1);
        if($day[1]<$mon[1]){
            $nowMonth =$month;
        }
        $jin = new JinDie();
        $config = new Config();
        $message = new message();
        $merchantDayModel = new MerchantDayMoney();
        $MerchantMonthMoney = new MerchantMonthMoney();
        // 当前时间是否为 00：10 - 00:40
        if (time() >= $start_time && time() <= $end_time) {
            // 查询所有商户
            $Allmerchant = (new WatchMaintain())->with(['merchant'])->where(['type' => 1, 'status' => 1])->select()->toArray();
            $configInfo = $config->find(1)->toArray();
            $money = (new MerchantMoney())->where('dateTime', $monthsss)->find();
            if (!empty($Allmerchant)) {
                foreach ($Allmerchant as $v) {
                    $data_day = [];
                    $EleInfo = [];
                    $frozen_balance = 0;
                    $data = [];
                    $Electricity = [];
                    $res = [];
                    $first = [];
                    $dataInfo = [];
                    $EleInfo = [];
                    $dayInfo = [];
                    $oneDayMoney = 0; //上月的消费   oOGTi4lmrNHNdUY4aP-nX3am7O2k
                    if ($v['is_sole'] == 1) { //单一用电的
                        $dandata = [
                            "water_or_electricity" => 2,
                            'type' => 3,
                            'day_month' => 2,
                            'pointId' => $v['point'],
                            'startdate' => $YesterDay,
                            'enddate' => ''
                        ];
                        $EleInfo = $jin->getElectricity($dandata);
                        if (empty($EleInfo)) {
                            $EleInfo = $jin->getElectricity($dandata);
                        }
                        $danlog = (new KwhWaterLog())->where(['datelog' => $YesterDay, 'pointId' => $v['pointId']])->find();
                        if (empty($danlog) && !empty($EleInfo)) {
                            $dandata = [
                                'merchant_id' => $v['merchant_id'],
                                'pointId' => $v['pointId'],
                                'dataTime' => $nowMonth,
                                'end' => $EleInfo['endbm'],
                                'start' => $EleInfo['startbm'],
                                'create_time' => time(),
                                'use_type' => $v['use_type'],
                                'datelog' => $YesterDay
                            ];
                            (new KwhWaterLog())->save($dandata);
                            if (in_array($v['merchant_id'],explode(',',$merchant_list['merchant_ids']))) {//指定用户催费
                                if (!empty($money)) {
//                                    $frozen_balance = bcmul(bcsub($EleInfo['endbm'], $EleInfo['startbm'], 2), $money['linmoney'], 2);
                                    $danprice = (new MonthSoleElectricityLog())->order('dataTime desc')->where(['merchant_id'=>$v['merchant_id'],'status'=>1])->value('price');
                                    if(!empty($danprice)){
                                        $money['linmoney'] = $danprice;
                                    }
                                    $frozen_balance = bcmul($EleInfo['energyp'], $money['linmoney'], 2);
                                    if ($v['balance'] > 0 && !empty($v['merchant_id'])) {
                                        $balance = bcsub($v['balance'], $frozen_balance * 100);
//                                    //查今天是否有记录
                                        $dayInfo = $merchantDayModel->where(['merchant_id' => $v['merchant_id'],'pointId'=>$v['pointId'], 'day' => $YesterDay])->find();
                                        $monthInfo = $MerchantMonthMoney->where(['merchant_id' => $v['merchant_id'], 'dataTime' => $nowMonth])->find();
                                        if (empty($dayInfo)) {
                                            (new Merchant())->where('id', $v['merchant_id'])->update(['balance' => $balance]);
                                            (new Merchant())->where('id', $v['merchant_id'])->inc('frozen_balance', $frozen_balance * 100)->update();
                                            $merchantDay['merchant_id'] = $v['merchant_id'];
                                            $merchantDay['code'] = $v['code'];
                                            $merchantDay['balance']  = $v['balance'];
                                            $merchantDay['pointId']  = $v['pointId'];
                                            $merchantDay['use_yue']  = $balance;
                                            $merchantDay['name']  = $v['name'];
                                            $merchantDay['company']  = $v['company'];
                                            $merchantDay['money']  = $frozen_balance * 100;
                                            $merchantDay['dataTime']  = $nowMonth;
                                            $merchantDay['day'] = $YesterDay;
                                            $merchantDay['create_time'] = time();
                                            $merchantDayModel->insert($merchantDay);
                                            if(empty($monthInfo)){
                                                unset($merchantDay['day']);
                                                unset($merchantDay['pointId']);
                                                $MerchantMonthMoney->insert($merchantDay);
                                            }else{
                                                $MerchantMonthMoney->update([
                                                    'money' => bcadd($monthInfo['money'], bcmul($frozen_balance, 100)),
                                                    'balance' => bcadd($v['balance'],$v['frozen_balance']),
                                                    'use_yue' => $balance,
                                                ], ['id' => $monthInfo['id']]);
                                            }
                                        }
//                                        else {
//                                            $yingMoney = bcadd($dayInfo['money'], bcmul($frozen_balance, 100));
//                                            $merchantDayModel->update([
//                                                'money' => $yingMoney,
//                                                'balance' => bcadd($v['balance'],$v['frozen_balance']),
//                                                'use_yue' => $balance
//                                            ], ['id' => $dayInfo['id']]);
//                                            $MerchantMonthMoney->update([
//                                                'money' => bcadd($monthInfo['money'], bcmul($frozen_balance, 100)),
//                                                'balance' => bcadd($v['balance'],$v['frozen_balance']),
//                                                'use_yue' => $balance,
//                                            ], ['id' => $monthInfo['id']]);
//                                        }
                                    }
                                }
                            }

                        }

                    } else {
                        if ($v['point'] == '117467') {
//                    if ($v['use_type'] == 2 || $v['use_type'] == 1 || $v['use_type'] == 4 || $v['use_type'] == 5|| $v['is_normal']==2||$v['point']=='117467') {
                            $dandata = [
                                "water_or_electricity" => 2,
                                'type' => 1,
                                'day_month' => 2,
                                'pointId' => $v['point'],
                                'startdate' => $YesterDay,
                                'enddate' => ''
                            ];
                            $EleInfo = $jin->getElectricity($dandata);
                            if (empty($EleInfo)) {
                                $EleInfo = $jin->getElectricity($dandata);
                            }
                            $first = (new KwhLog())->where(['pointId' => $v['pointId'], 'merchant_id' => $v['merchant_id'], 'datelog' => $YesterDay])->find();
                            if (empty($first) && !empty($EleInfo)) {
                                $dataInfo = [
                                    'merchant_id' => $v['merchant_id'],
                                    'pointId' => $v['pointId'],
                                    'pointName' => $EleInfo['name'],
                                    'dataTime' => $nowMonth,
                                    'fengStart' => 0,
                                    'fengEnd' => 0,
                                    'fengPower' => $EleInfo['feng']['energyp'],
                                    'guStart' => 0,
                                    'guEnd' => 0,
                                    'guPower' => $EleInfo['gu']['energyp'],
                                    'pingStart' => 0,
                                    'pingEnd' => 0,
                                    'pingPower' => $EleInfo['ping']['energyp'],
                                    'rate' => $v['rate'],
                                    'use_type' => $v['use_type'],
                                    'updateTime' => time(),
                                    'create_time' => time(),
                                    'datelog' => $YesterDay
                                ];
                                (new KwhLog())->save($dataInfo);
                            }
                        } else {
                            if ($v['use_type'] == 3 || $v['use_type'] == 6) {
                                $dandata = [
                                    "water_or_electricity" => 2,
                                    'type' => 2,
                                    'day_month' => 2,
                                    'pointId' => $v['point'],
                                    'startdate' => $YesterDay,
                                    'enddate' => ''
                                ];
                                $EleInfo = $jin->getElectricity($dandata);
                                if (empty($EleInfo)) {
                                    $EleInfo = $jin->getElectricity($dandata);
                                }
                                $first = (new KwhLog())->where(['pointId' => $v['pointId'],  'datelog' => $YesterDay])->find();
                                if (empty($first) && !empty($EleInfo)) {
                                    if (empty($EleInfo['feng']['startbm']) && empty($EleInfo['gu']['startbm']) && empty($EleInfo['ping']['startbm'])) {

                                    } else {
                                        $dataInfo = [
                                            'merchant_id' => $v['merchant_id'],
                                            'pointId' => $v['pointId'],
                                            'pointName' => $EleInfo['name'],
                                            'dataTime' => $nowMonth,
                                            'fengStart' => $EleInfo['feng']['startbm'],
                                            'fengEnd' => $EleInfo['feng']['endbm'],
                                            'fengPower' => $EleInfo['feng']['energyp'],
                                            'guStart' => $EleInfo['gu']['startbm'],
                                            'guEnd' => $EleInfo['gu']['endbm'],
                                            'guPower' => $EleInfo['gu']['energyp'],
                                            'pingStart' => $EleInfo['ping']['startbm'],
                                            'pingEnd' => $EleInfo['ping']['endbm'],
                                            'pingPower' => $EleInfo['ping']['energyp'],
                                            'rate' => $v['rate'],
                                            'use_type' => $v['use_type'],
                                            'updateTime' => time(),
                                            'create_time' => time(),
                                            'datelog' => $YesterDay
                                        ];
                                        (new KwhLog())->save($dataInfo);
                                    }
                                    $power = [
                                        'fengEnd' => $EleInfo['feng']['endbm'],
                                        'fengStart' => $EleInfo['feng']['startbm'],
                                        'guEnd' => $EleInfo['gu']['endbm'],
                                        'guStart' => $EleInfo['gu']['startbm'],
                                        'pingEnd' => $EleInfo['ping']['endbm'],
                                        'pingStart' => $EleInfo['ping']['startbm'],
                                        'rate' => $v['rate'],
                                    ];
                                    if (in_array($v['merchant_id'],explode(',',$merchant_list['merchant_ids']))) {//指定用户催费
                                        if (!empty($money)) {
                                            if($v['use_type']==6){
                                                $money['tmoney'] =  $money['stmoney'];
                                            }
                                            $frozen_balance = rate($power, $money);
                                            if ($v['balance'] > 0 && !empty($v['merchant_id'])) {
                                                $balance = bcsub($v['balance'], bcmul($frozen_balance['allMoney'], 100));
                                                //查今天是否有记录
                                                $dayInfo = $merchantDayModel->where(['merchant_id' => $v['merchant_id'],'pointId'=>$v['pointId'], 'day' => $YesterDay])->find();
                                                $monthInfo = $MerchantMonthMoney->where(['merchant_id' => $v['merchant_id'], 'dataTime' => $nowMonth])->find();
                                                if (empty($dayInfo)) {
                                                    (new Merchant())->where('id', $v['merchant_id'])->update(['balance' => $balance]);
                                                    (new Merchant())->where('id', $v['merchant_id'])->inc('frozen_balance', $frozen_balance['allMoney'] * 100)->update();
                                                    $merchantDay['merchant_id'] = $v['merchant_id'];
                                                    $merchantDay['pointId']  = $v['pointId'];
                                                    $merchantDay['money']  = $frozen_balance['allMoney'] * 100;
                                                    $merchantDay['code'] = $v['code'];
                                                    $merchantDay['balance']  = $v['balance'];
                                                    $merchantDay['use_yue']  = $balance;
                                                    $merchantDay['name']  = $v['name'];
                                                    $merchantDay['company']  = $v['company'];
                                                    $merchantDay['day'] = $YesterDay;
                                                    $merchantDay['dataTime'] = $nowMonth;
                                                    $merchantDay['create_time'] = time();
                                                    $merchantDayModel->insert($merchantDay);
                                                    if(empty($monthInfo)){
                                                        unset($merchantDay['day']);
                                                        unset($merchantDay['pointId']);
                                                        $MerchantMonthMoney->insert($merchantDay);
                                                    }else{
                                                        $MerchantMonthMoney->update([
                                                            'money' => bcadd($monthInfo['money'], bcmul($frozen_balance['allMoney'], 100)),
                                                            'balance' => $v['balance'],
                                                            'use_yue' => $balance,
                                                        ], ['id' => $monthInfo['id']]);
                                                    }
                                                }
//                                                else {
//                                                    $yingMoney = bcadd($dayInfo['money'], bcmul($frozen_balance['allMoney'], 100));
//                                                    $merchantDayModel->update([
//                                                        'money' => $yingMoney,
//                                                        'balance' => bcadd($v['balance'],$v['frozen_balance']),
//                                                        'use_yue' => $balance,
//                                                    ], ['id' => $dayInfo['id']]);
//                                                    $MerchantMonthMoney->update([
//                                                        'money' => bcadd($monthInfo['money'], bcmul($frozen_balance['allMoney'], 100)),
//                                                        'balance' => bcadd($v['balance'],$v['frozen_balance']),
//                                                        'use_yue' => $balance,
//                                                    ], ['id' => $monthInfo['id']]);
//                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (in_array($v['merchant_id'],explode(',',$merchant_list['merchant_ids']))) {//指定用户催费
                        $water = $merchantDayModel->where(['merchant_id' => $v['merchant_id'], 'day' => $YesterDay, 'is_send' => 0])->sum('money');
                        $ele = $merchantDayModel->where(['merchant_id' => $v['merchant_id'], 'day' => $YesterDay, 'is_send' => 0])->sum('water_money');
                        $yesMoney = $water+$ele;
                        if ($yesMoney>0) {
                            //商户余额小于昨天的用电费用
                            if($v['balance']<$yesMoney){
                                $Energy = new Energy();
                                $watch= new WatchLog();
                                $remote_disconnect = [];
                                $remote_disconnect = [
                                    "pointId" => $v['pointId'],
                                    "operType" => 1 //1 拉闸2 合闸
                                ];
                                Log::info('每天早上商户余额不足请求数据:'.json_encode($remote_disconnect));
                                // 查询月电费接口
                                $port_data_res = $Energy->universalfunction('remote_disconnect', $remote_disconnect);
                                if(empty($port_data_res)||$port_data_res==false){
                                    $port_data_res = $Energy->universalfunction('remote_disconnect', $remote_disconnect);
                                }
                                if(isset($port_data_res)){
                                    $watch->pointId = $remote_disconnect['pointId'];
                                    $watch->operType = $remote_disconnect['operType'];
                                    $watch->return_info = json_encode($port_data_res);
                                    $watch->create_time = time();
                                    $watch->save();
                                }
                            }
                            if ($v['balance'] < bcmul($yesMoney, $configInfo['date_time'])) {
                                $senddata['company'] = $v['company'];
                                $senddata['balance'] = $v['balance'] / 100;
                                $senddata['openid'] = $v['openid'];
                                $message->arrearage($senddata);
                                $merchantDayModel->update(['is_send' => 1], ['merchant_id' =>$v['merchant_id'],'day' => $YesterDay]);
                            }
                        }
                    }
                    //每月初读取商户水电表
                if (time() >= strtotime(date('Y-m-03')) && time() <= strtotime(date('Y-m-12'))) {//时间处于当月1号10分到1点10分之间
                    if ($v['is_sole'] == 1) {
                        $data = [
                            "water_or_electricity" => 2,
                            'type' => 3,
                            'day_month' => 3,
                            'pointId' => $v['point'],
                            'startdate' => $month,
                            'enddate' => ''
                        ];
                        $port_data = $jin->getElectricity($data);
                        if (empty($port_data)) {
                            $port_data = $jin->getElectricity($data);
                        }
                        $danyi = (new MonthSoleElectricityLog())->where(['dataTime' => $month, 'pointId' => $v['pointId']])->find();
                        if (empty($danyi) && !empty($port_data)) {
                            $dandata = [
                                'merchant_id' => $v['merchant_id'],
                                'pointId' => $v['pointId'],
                                'pointName' => $v['pointName'],
                                'dataTime' => $month,
                                'rate' => $v['rate'],
                                'totalPower' => bcmul(bcsub($port_data['endbm'], $port_data['startbm'], 2), $v['rate'], 2),
                                'zongEnd' => $port_data['endbm'],
                                'zongMoney' => 0,
                                'zongPower' => 0,
                                'code' => isset($v['code']) ? $v['code'] : '',
                                'zongStart' => $port_data['startbm'],
                                'create_time' => time(),
                            ];
                            (new MonthSoleElectricityLog())->save($dandata);
                        }
                        $is_reading_log = (new MerchantReadingLog())->where(['pointId'=>$v['pointId'],'in_type'=>1])->find();
                        $is_reading_month = (new MonthSoleElectricityLog())->where(['dataTime'=>$month,'merchant_id'=>$v['merchant_id'],'pointId'=>$v['pointId']])->find();
                        if(!empty($is_reading_log)&&empty($is_reading_month)&&!empty($port_data)){
                            $sole_first = [];
                            $sole_first = [
                                'zongStart' => $is_reading_log['sole'],
                                'zongEnd' => $port_data['endbm'],
                                'pointId' => $v['pointId'],
                                'pointName' => $v['pointName'],
                                'rate' => $v['rate'],
                                'merchant_id' =>$is_reading_log['new_merchant_id'],
                                'dataTime' => $month,
                                'create_time' => time(),
                                'zongMoney' => 0,
                                'zongPower' => 0,
                                'code' => isset($v['code']) ? $v['code'] : '',
                                'totalPower'=>bcsub($port_data['endbm'], $is_reading_log['sole'], 2)
                            ];
                            Log::info('单一电表入场二次记录:'.json_encode($sole_first));
                            (new MonthSoleElectricityLog())->save($sole_first);
                        }
                    } else {
                        if ($v['use_type'] == 2 || $v['use_type'] == 1 || $v['use_type'] == 4 || $v['use_type'] == 5 || $v['is_normal'] == 2 || $v['point'] == '117467') {
                            $data = [
                                "water_or_electricity" => 2,
                                'type' => 1,
                                'day_month' => 3,
                                'pointId' => $v['point'],
                                'startdate' => $month,
                                'enddate' => ''
                            ];
                            $res = [];
                            $res = $jin->getElectricity($data);
                            if (empty($res)) {
                                $res = $jin->getElectricity($data);
                            }
                            $first = (new MonthElectricityDegree())->where(['pointId' => $v['pointId'], 'dataTime' => $month])->find();
                            if (empty($first) && !empty($res)) {
                                $Electricity = [];
                                $Electricity = [
                                    'merchant_id' => $v['merchant_id'],
                                    'pointId' => $v['pointId'],
                                    'pointName' => $res['name'],
                                    'dataTime' => $month,
                                    'fengStart' => 0,
                                    'fengEnd' => 0,
                                    'fengPower' => $res['feng'],
                                    'guStart' => 0,
                                    'guEnd' => 0,
                                    'guPower' => $res['gu'],
                                    'pingStart' => 0,
                                    'pingEnd' => 0,
                                    'pingPower' => $res['ping'],
                                    'rate' => $v['rate'],
                                    'use_type' => $v['use_type'],
                                    'create_time' => time(),
                                ];
                                (new MonthElectricityDegree())->save($Electricity);
                            }
                        } else {
                            $data = [
                                "water_or_electricity" => 2,
                                'type' => 2,
                                'day_month' => 3,
                                'pointId' => $v['point'],
                                'startdate' => $month,
                                'enddate' => ''
                            ];
                            $res = [];
                            $res = $jin->getElectricity($data);
                            if (empty($res)) {
                                $res = $jin->getElectricity($data);
                            }
                            $first = (new MonthElectricityDegree())->where(['pointId' => $v['pointId'],  'dataTime' => $month])->find();
                            $lastMonth = (new MonthElectricityDegree())->order('dataTime desc')->where(['pointId' => $v['pointId']])->find();
                            if (empty($first) && !empty($res)) {
                                if (($res['feng']['startbm']=='null'&&$res['feng']['startbm']!=0)||!$res['feng']['endbm']) {

                                } else {
                                    $Electricity = [];
                                    $Electricity = [
                                        'merchant_id' => $v['merchant_id'],
                                        'pointId' => $v['pointId'],
                                        'pointName' => $res['name'],
                                        'dataTime' => $month,
                                        'fengStart' => $res['feng']['startbm'],
                                        'fengEnd' => $res['feng']['endbm'],
                                        'fengPower' => $res['feng']['energyp'],
                                        'guStart' => $res['gu']['startbm'],
                                        'guEnd' => $res['gu']['endbm'],
                                        'guPower' => $res['gu']['energyp'],
                                        'pingStart' => $res['ping']['startbm'],
                                        'pingEnd' => $res['ping']['endbm'],
                                        'pingPower' => $res['ping']['energyp'],
                                        'rate' => $v['rate'],
                                        'use_type' => $v['use_type'],
                                        'create_time' => time(),
                                    ];
                                    if (!empty($lastMonth)) {
                                        $Electricity['guStart'] = $lastMonth['guEnd'];
                                        $Electricity['guPower'] = bcmul(bcsub($res['gu']['endbm'], $lastMonth['guEnd'], 2), $v['rate'], 2);
                                    }
                                    (new MonthElectricityDegree())->save($Electricity);
                                }

                            }else{
                                $is_reading_log = (new MerchantReadingLog())->where(['pointId'=>$v['pointId'],'in_type'=>1])->find();
                                $is_reading_month = (new MonthElectricityDegree())->where(['dataTime'=>$month,'merchant_id'=>$v['merchant_id'],'pointId'=>$v['pointId']])->find();
                                if(!empty($is_reading_log)&&empty($is_reading_month)&&!empty($res)){
                                    $ele_first = [];
                                    $ele_first = [
                                        'merchant_id' =>$is_reading_log['new_merchant_id'],
                                        'pointId' => $v['pointId'],
                                        'pointName' => $res['name'],
                                        'dataTime' => $month,
                                        'fengStart' => $is_reading_log['fengpower'],
                                        'fengEnd' => $res['feng']['endbm'],
                                        'fengPower' => 0,
                                        'guStart' => $is_reading_log['gupower'],
                                        'guEnd' => $res['gu']['endbm'],
                                        'guPower' => 0,
                                        'pingStart' => $is_reading_log['pingpower'],
                                        'pingEnd' => $res['ping']['endbm'],
                                        'pingPower' =>0,
                                        'rate' => $v['rate'],
                                        'use_type' => $v['use_type'],
                                        'create_time' => time(),
                                    ];
                                    Log::info('费率电表入场二次记录:'.json_encode($ele_first));
                                    (new MonthElectricityDegree())->save($ele_first);
                                }
                            }
                        }
                    }

                }
            }
        }
    }

    }
}